package whereRU.frontEnd;



import whereRU.frontEnd.R;
import database.CourseDbAdapter;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Activity for viewing a user's course schedule
 */
public class CourseScheduleActivity extends FragmentActivity
				implements SetAlarmDialog.SetAlarmDialogListener {
	
	public static final String EXTRA_COURSE_ID = "sp.whereru.COURSE_ID";

	public static final int LIST_EDIT = 0;
	public static final int LIST_DELETE = 1;
	public static final int LIST_ALARM = 2;
	
	CourseDbAdapter mDbHelper;
	ListView lvCourses;
	CourseAlarmManager alarmManager;
	

	/**
	 * Set up the views to show the users schedule.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.course_schedule);
		mDbHelper = new CourseDbAdapter(this);
		mDbHelper.open();
		alarmManager = new CourseAlarmManager(this);
		
		lvCourses = (ListView) findViewById(R.id.coursesList);
		lvCourses.setEmptyView(findViewById(R.id.empty_list));
		
		fillData();
		
		final Intent intent = new Intent(this, ViewCourseActivity.class);
		
		// create a click listener for the list view so individual courses can be clicked
		AdapterView.OnItemClickListener lvClickListener = new ListView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> list, View view, int position, long id) {
				intent.putExtra(EXTRA_COURSE_ID, id);
				startActivity(intent);
			}
		};
		
		// create a long click listener for the list view
		AdapterView.OnItemLongClickListener lvLongClickListener = new ListView.OnItemLongClickListener() {
			// If a user clicks a course
			public boolean onItemLongClick(AdapterView<?> list, View view, int position, long id) {
				Cursor cCourse = mDbHelper.fetchCourse(id);
				final String courseName = cCourse.getString(cCourse.getColumnIndex(CourseDbAdapter.KEY_NAME));
				final long courseId = cCourse.getLong(cCourse.getColumnIndex(CourseDbAdapter.KEY_ROWID));

				// display the dialog box with options
				AlertDialog.Builder builder = new AlertDialog.Builder(CourseScheduleActivity.this);
				builder.setTitle(courseName)
				.setItems(R.array.courseOptions, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						switch(which) {
						case LIST_EDIT:
							showEditCourseActivity(courseId);
							break;
						case LIST_DELETE:
							showDeleteDialog(courseName, courseId);
							break;
						case LIST_ALARM:
							showAlarmDialog(courseId);
							break;
						}
					}
				});
				Dialog courseOptionsMenu = builder.create();
				courseOptionsMenu.show();
				return true;
			}
		};
		
		// set the click listeners to the list view
		lvCourses.setOnItemClickListener(lvClickListener);
		lvCourses.setOnItemLongClickListener(lvLongClickListener);
	}

	/**
	 * Method that switches activity to AddCourseActivity
	 * @param view
	 */
	public void addClass(View view) {
		startActivity(new Intent(this, AddCourseActivity.class));    	
	}

	/**
	 * Called when the activity is destroyed.
	 * Close the database.
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();
		mDbHelper.close();
	}

	/** 
	 * Refreshes the list with current course data from the database
	 */
	private void fillData() {
		// Get all of the courses from the database and return a cursor
		Cursor c = mDbHelper.fetchAllCourses();
		startManagingCursor(c);

		String[] from = new String[] { CourseDbAdapter.KEY_NAME, CourseDbAdapter.KEY_BUILDING, 
				CourseDbAdapter.KEY_ROOM, CourseDbAdapter.KEY_START,
				CourseDbAdapter.KEY_END, CourseDbAdapter.KEY_DAYS };
		int[] to = new int[] { R.id.list_course, R.id.list_building, R.id.list_room, 
				R.id.list_start, R.id.list_end, R.id.list_days };

		// create a cursor adapter and set it to display using our row layout
		SimpleCursorAdapter coursesAdapter =
				new SimpleCursorAdapter(this, R.layout.courses_row, c, from, to);

		// attaches a view binder that changes the time value stored in the database
		// (i.e. 750) to a human readable format (i.e. 4:30PM)
		coursesAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
			public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
				int startTimeIndex = cursor.getColumnIndex(CourseDbAdapter.KEY_START);
				int endTimeIndex = cursor.getColumnIndex(CourseDbAdapter.KEY_END);
				
				// if the current view being applied is the start time
				if (startTimeIndex == columnIndex) {
					int time = cursor.getInt(startTimeIndex);
					SimpleTime sTime = new SimpleTime(time);
					TextView textView = (TextView) view;
					textView.setText(sTime.toString() + " - ");
					return true;
				}
				else if (endTimeIndex == columnIndex) {
					int time = cursor.getInt(endTimeIndex);
					SimpleTime sTime = new SimpleTime(time);
					TextView textView = (TextView) view;
					textView.setText(sTime.toString());
					return true;
				}
				return false;
			}
		});

		// set the adapter for the list view to the cursor adapter
		lvCourses.setAdapter(coursesAdapter);
	}

	/**
	 * Build and show the dialog that confirms a user really wants
	 * to delete a course from their schedule
	 * @param courseName	the name of the course
	 * @param row			the row id of the course
	 */
	private void showDeleteDialog(final String courseName, final long courseId) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Confirm Delete")
		.setMessage("Are you sure you want to delete " + courseName + " from your schedule?")
		.setPositiveButton(R.string.dialog_delete, new DialogInterface.OnClickListener() {
			// user deletes the course
			public void onClick(DialogInterface dialog, int id) {
				mDbHelper.deleteCourse(courseId); 	// delete from database
				alarmManager.cancelAlarm(courseId);	// cancel any alarm attached to the course
				Toast toast = Toast.makeText(getApplicationContext(), 
						"\"" + courseName +"\" deleted from schedule", 
						Toast.LENGTH_SHORT); 
				toast.show();
				fillData();
			}
		})
		.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
			// user cancelled the dialog
			public void onClick(DialogInterface dialog, int id) { }
		});

		AlertDialog confirmDelete = builder.create();
		confirmDelete.show();
	}

	/**
	 * Shows the dialog for a user to set an alarm for a specific course
	 * @param courseId	the courseId associated with the selected course
	 */
	private void showAlarmDialog(long courseId) {
		boolean isSet = mDbHelper.isAlarmSet(courseId);
		int alarmDelay = mDbHelper.getAlarmDelay(courseId);
		DialogFragment dialog = SetAlarmDialog.newInstance(this, courseId, isSet, alarmDelay);
		
		dialog.show(getSupportFragmentManager(), "SetAlarmDialog");
	}
	
	/**
	 * Switches to AddCourseActivity when the user chooses to edit a course.
	 * Sends an intent with the courseId of which to edit
	 * @param courseId	the courseId of the course being edited
	 */
	private void showEditCourseActivity(long courseId) {
		Intent intent = new Intent(this, AddCourseActivity.class);
		intent.putExtra(EXTRA_COURSE_ID, courseId);
		startActivity(intent);		
	}

	/**
	 * Method is called when the user clicks the "OK" button when setting an alarm
	 */
	public void onSetAlarmDialogPositiveClick(DialogFragment dialog, long courseId) {
		int delay;
		Dialog d = dialog.getDialog();
		EditText et = (EditText) d.findViewById(R.id.et_alarmDelay);
		String text = et.getText().toString();
		if(text.equals(""))		
			delay = 0;
		else
			delay = Integer.parseInt(text);
		
		CheckBox checkbox = (CheckBox) d.findViewById(R.id.checkbox_alarm);
		mDbHelper.setAlarmDelay(courseId, delay);
		Course course = mDbHelper.returnCourse(courseId);
		
		// if user wants to set an alarm
		if(checkbox.isChecked()) {
			alarmManager.cancelAlarm(courseId);
			mDbHelper.toggleAlarm(courseId, true, delay);
			alarmManager.setAlarm(course);
			Toast toast = Toast.makeText(this, "Alarm has been set for " + delay 
					+ " minutes early for " + course.getName(), Toast.LENGTH_LONG);
			toast.show();
		}
		// user wants to cancel alarm
		else {
			mDbHelper.toggleAlarm(courseId, false, 0);
			alarmManager.cancelAlarm(courseId);
			Toast toast = Toast.makeText(this, "Alarm for " + course.getName() 
					+ " has been cancelled", Toast.LENGTH_LONG);
			toast.show();
		}
	}

	/**
	 * Method is called when the user clicks the "Cancel" button when setting an alarm
	 */
	public void onSetAlarmDialogNegativeClick(DialogFragment dialog, long courseId) {
		// user clicked cancel, do nothing
	}

}